import backtrader as bt

# backtrader趋势跟踪交易策略代码实现
class TrendFollowingStrategy(bt.Strategy):
    params = (("period", 20),)

    def __init__(self):
        self.dataclose = self.datas[0].close
        self.sma = bt.indicators.SimpleMovingAverage(
            self.datas[0], period=self.params.period
        )

    def next(self):
        if self.dataclose[0] > self.sma[0]:
            if self.position.size < 0:
                self.close()
            elif self.position.size == 0:
                self.buy()
        elif self.dataclose[0] < self.sma[0]:
            if self.position.size > 0:
                self.close()
            elif self.position.size == 0:
                self.sell()


if __name__ == "__main__":
    cerebro = bt.Cerebro()
    data = bt.feeds.GenericCSVData(
        dataname="your_data.csv",
        dtformat=("%Y-%m-%d"),
        datetime=0,
        open=1,
        high=2,
        low=3,
        close=4,
        volume=5,
        openinterest=-1,
    )
    cerebro.adddata(data)
    cerebro.addstrategy(TrendFollowingStrategy)
    cerebro.broker.setcash(100000.0)
    cerebro.broker.setcommission(commission=0.001)
    print("Starting Portfolio Value: %.2f" % cerebro.broker.getvalue())
    cerebro.run()
    print("Final Portfolio Value: %.2f" % cerebro.broker.getvalue())
